// LangPage.cpp

#include "StdAfx.h"

#include "Common/String/StringConvert.h"

#include "Common/String/ResourceString.h"

#include "HelpUtils.h"
#include "LangPage.h"
#include "resource.h"
#include "Common/Lang/LangUtils.h"
#include "Common/Registry/RegistryUtils.h"

#include <vector>

using namespace Common;

static Lang::CIDLangPair kIDLangPairs[] =
{
  { IDC_LANG_STATIC_LANG, 0x01000401}
};

static LPCWSTR kLangTopic = _T("fm/options.htm#language");

static CString NativeLangString(const CString &s)
{
  return _T(" (") + s + _T(')');
}

LRESULT CLangPage::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
  LangSetDlgItemsText(HWND(*this), kIDLangPairs, sizeof(kIDLangPairs) / sizeof(kIDLangPairs[0]));

  _langCombo.Attach(GetDlgItem(IDC_LANG_COMBO_LANG));

  CString s = Common::String::LoadString(IDS_LANG_ENGLISH) +
      NativeLangString(Common::String::LoadString(IDS_LANG_NATIVE));
  int index = (int)_langCombo.AddString(s);
  _langCombo.SetItemData(index, _paths.size());
  _paths.push_back(_T("-"));
  _langCombo.SetCurSel(0);

  std::vector<Lang::CLangEx> langs;
  LoadLangs(langs);
  for (size_t i = 0; i < langs.size(); i++)
  {
    const Lang::CLangEx &lang = langs[i];
    CString name, nationalName;
    if (!lang.Lang.GetMessage(0, name))
      name = lang.ShortName;
    if (lang.Lang.GetMessage(1, nationalName) && !nationalName.IsEmpty())
      name += NativeLangString(nationalName);

    index = (int)_langCombo.AddString(name);
    _langCombo.SetItemData(index, _paths.size());
    _paths.push_back(lang.ShortName);
    if (g_LangID.CompareNoCase(lang.ShortName) == 0)
      _langCombo.SetCurSel(index);
  }
  return TRUE;
}

int CLangPage::OnApply()
{
  int selectedIndex = _langCombo.GetCurSel();
  int pathIndex = (int)_langCombo.GetItemData(selectedIndex);
  Registry::SaveRegLang(_paths[pathIndex]);
  Lang::ReloadLang();
  LangWasChanged = true;
  return TRUE;
}

void CLangPage::OnHelp()
{
  ShowHelpWindow(NULL, kLangTopic);
}
